package com.cheer.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.common.Page;
import com.cheer.dao.MallShopDao;
import com.cheer.dto.MallShopAddDTO;
import com.cheer.dto.MallShopQueryDTO;
import com.cheer.dto.MallShopUpdateDTO;
import com.cheer.entity.MallOrderEntity;
import com.cheer.entity.MallShopEntity;
import com.cheer.enums.MallProductStatusEnum;
import com.cheer.exception.ServiceException;
import com.cheer.service.MallOrderService;
import com.cheer.service.MallProductService;
import com.cheer.service.MallShopService;
import com.cheer.vo.MallShopInfoVO;
import com.cheer.vo.MallShopListVO;
import com.cheer.vo.SimpleObjectVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service("mallShopService")
public class MallShopServiceImpl extends ServiceImpl<MallShopDao, MallShopEntity> implements MallShopService {

    @Autowired
    private MallShopDao mallShopDao;

    @Autowired
    private MallProductService mallProductService;

    @Autowired
    private MallOrderService mallOrderService;

    @Override
    public Page<MallShopListVO> listByQueryCondition(MallShopQueryDTO shopQueryDTO) {
        // 分页查询商户信息
        IPage<MallShopEntity> page = mallShopDao.selectPageByQueryCondition(shopQueryDTO);

        // 转换商户vo
        List<MallShopListVO> shopList = page.getRecords().stream()
                .map(shop -> {

                    // 基础信息
                    MallShopListVO shopListVO = new MallShopListVO()
                            .setId(shop.getId())
                            .setName(shop.getName())
                            .setCreateTime(DateUtil.formatDateTime(shop.getCreateTime()))
                            .setContactPerson(shop.getContactPerson())
                            .setPhone(shop.getPhone());

                    // 商品数量
                    shopListVO.setProductCount(mallProductService.countByShopIdAndStatus(shop.getId(),
                            MallProductStatusEnum.PASSED.getCode()));

                    // 售出数量，金额
                    List<MallOrderEntity> orderList = mallOrderService.listFinishedSimplyByShopId(shop.getId());
                    int count = 0;
                    BigDecimal amount = new BigDecimal(0);
                    for (MallOrderEntity order : orderList) {
                        count += order.getQuantity();
                        if (order.getPrice() != null) {
                            amount = amount.add(order.getPrice().multiply(new BigDecimal(order.getQuantity())));
                        }
                    }
                    shopListVO.setSaleCount(count)
                            .setSaleAmount(amount.stripTrailingZeros().toPlainString());

                    return shopListVO;
                })
                .collect(Collectors.toList());

        return new Page<>(page, shopList);
    }

    @Override
    public void add(MallShopAddDTO shopAddDTO) {
        MallShopEntity shopEntity = new MallShopEntity()
                .setName(shopAddDTO.getName())
                .setContactPerson(shopAddDTO.getContactPerson())
                .setPhone(shopAddDTO.getPhone())
                .setContactPhone(shopAddDTO.getPhone())
                .setType(shopAddDTO.getType());
        mallShopDao.insert(shopEntity);
    }

    @Override
    public MallShopInfoVO info(Long id) {
        MallShopEntity shop = mallShopDao.selectById(id);
        if (shop == null) {
            throw new ServiceException("商户不存在");
        }

        return new MallShopInfoVO()
                .setId(shop.getId())
                .setName(shop.getName())
                .setContactPerson(shop.getContactPerson())
                .setPhone(shop.getContactPhone())
                .setType(shop.getType());
    }

    @Override
    public void update(MallShopUpdateDTO shopUpdateDTO) {
        MallShopEntity updateShop = new MallShopEntity()
                .setId(shopUpdateDTO.getId())
                .setName(shopUpdateDTO.getName())
                .setContactPerson(shopUpdateDTO.getContactPerson())
                .setContactPhone(shopUpdateDTO.getPhone())
                .setType(shopUpdateDTO.getType());

        mallShopDao.updateById(updateShop);
    }

    @Override
    @Transactional
    public void delete(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        mallShopDao.deleteBatchIds(ids);

        // 删除商品
        mallProductService.deleteByShopIds(ids);
    }

    @Override
    public MallShopEntity getByPhone(String phone) {
        return mallShopDao.selectOneByPhone(phone);
    }

    @Override
    public List<SimpleObjectVO> listAllSimply() {
        List<MallShopEntity> shopList = mallShopDao.selectName();

        return shopList.stream()
                .map(shopEntity -> new SimpleObjectVO()
                        .setId(shopEntity.getId())
                        .setName(shopEntity.getName()))
                .collect(Collectors.toList());
    }

}